package com.inspsys.inspection.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.inspsys.inspection.mapper.InspectionTaskMapper;
import com.alibaba.fastjson2.JSONObject;
import com.inspsys.common.config.InspSysConfig;
import com.inspsys.common.utils.DateUtils;
import com.inspsys.common.utils.file.ImageUtils;
import com.inspsys.inspection.domain.InspectionTask;
import com.inspsys.inspection.domain.bo.TaskBO;
import com.inspsys.inspection.service.IInspectionTaskService;

/**
 * 巡检任务Service业务层处理
 *
 * @author inspsys
 * @date 2025-01-08
 */
@Service
public class InspectionTaskServiceImpl implements IInspectionTaskService {

    @Autowired
    private InspectionTaskMapper inspectionTaskMapper;

    @Resource
    PdfGeneratorService pdfGeneratorService;

    /**
     * 查询巡检任务
     *
     * @param id 巡检任务主键
     * @return 巡检任务
     */
    @Override
    public InspectionTask selectInspectionTaskById(Long id) {
        return inspectionTaskMapper.selectInspectionTaskById(id);
    }

    /**
     * 查询巡检任务列表
     *
     * @param inspectionTask 巡检任务
     * @return 巡检任务
     */
    @Override
    public List<InspectionTask> selectInspectionTaskList(InspectionTask inspectionTask) {
        return inspectionTaskMapper.selectInspectionTaskList(inspectionTask);
    }

    /**
     * 新增巡检任务
     *
     * @param inspectionTask 巡检任务
     * @return 结果
     */
    @Override
    public int insertInspectionTask(InspectionTask inspectionTask) {
        StringBuffer orderNumerSb = new StringBuffer(DateUtils.dateTimeNow("yyyyMMddHHmm"));
        orderNumerSb.append("/").append(inspectionTask.getTaskType());
        orderNumerSb.append("/").append(inspectionTask.getPlatform());
        orderNumerSb.append("/").append(inspectionTask.getSection());
        inspectionTask.setOrderNumber(orderNumerSb.toString());
        return inspectionTaskMapper.insertInspectionTask(inspectionTask);
    }

    /**
     * 修改巡检任务
     *
     * @param inspectionTask 巡检任务
     * @return 结果
     */
    @Override
    public int updateInspectionTask(InspectionTask inspectionTask) {
        return inspectionTaskMapper.updateInspectionTask(inspectionTask);
    }

    /**
     * 批量删除巡检任务
     *
     * @param ids 需要删除的巡检任务主键
     * @return 结果
     */
    @Override
    public int deleteInspectionTaskByIds(Long[] ids) {
        return inspectionTaskMapper.deleteInspectionTaskByIds(ids);
    }

    /**
     * 删除巡检任务信息
     *
     * @param id 巡检任务主键
     * @return 结果
     */
    @Override
    public int deleteInspectionTaskById(Long id) {
        return inspectionTaskMapper.deleteInspectionTaskById(id);
    }

    /**
     * 查询缺陷检测结果
     *
     * @param vo 检测请求
     * @return
     */
    @Override
    public List<JSONObject> queryDetectResult(String orderNumber) {
        File[] files = getDetectFilePathList(orderNumber);
        List<JSONObject> detectResultList = new ArrayList<>();
        for (File file : files) {
            JSONObject object = new JSONObject();
            object.put("name", file.getName());
            object.put("base64Img", ImageUtils.encodeImageToBase64WithExtension(file.getAbsolutePath()));
            detectResultList.add(object);
        }
        return detectResultList;
    }

    /**
     * 导出工单报告
     *
     * @param inspectionTask 巡检任务
     * @return
     * @throws Exception
     */
    @Override
    public byte[] exportReport(InspectionTask inspectionTask) throws Exception {
        if (Objects.isNull(inspectionTask) || inspectionTask.getId() == null) {
            throw new Exception("导出失败，缺少参数");
        }
        InspectionTask task = inspectionTaskMapper.selectInspectionTaskById(inspectionTask.getId());
        if (Objects.isNull(task)) {
            throw new Exception("导出失败，没找到任务数据");
        }
        // 获取检测结果
        File[] files = getDetectFilePathList(task.getOrderNumber());
        TaskBO taskBO = new TaskBO();
        BeanUtils.copyProperties(task, taskBO);
        List<String> filePathList = new ArrayList<>();
        for (File file : files) {
            filePathList.add(file.getAbsolutePath());
        }
        taskBO.setDetectResultImageList(filePathList);
        return pdfGeneratorService.generateInspectionReport(taskBO);
    }

    /**
     * 根据工单号获取文件
     * 
     * @param orderNumber
     * @return
     */
    private File[] getDetectFilePathList(String orderNumber) {
        String[] detectPaths = orderNumber.split("/");

        StringBuilder detectPath = new StringBuilder();
        for (int i = 0; i < detectPaths.length; i++) {
            detectPath.append(detectPaths[i]);
            if (i != detectPaths.length - 1) {
                detectPath.append(File.separator);
            }
        }
        String detectFile = InspSysConfig.getDetectPath() + File.separator + detectPath.toString();
        File detectDir = new File(detectFile);
        if (!detectDir.exists() || !detectDir.isDirectory()) {
            // return "检测路径不存在或不是目录";
            return new File[0];
        }
        return detectDir.listFiles();
    }

}
